package com.zhentao.controller;

import com.alibaba.fastjson2.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.easysdk.factory.Factory;
import com.zhentao.config.AliPayConfig;
import com.zhentao.service.OrdersService; // 假设你有这个service
import com.zhentao.mapper.OrdersMapper;
import com.zhentao.pojo.Orders;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/payment")
public class AlipayController {

    private static final Logger logger = LoggerFactory.getLogger(AlipayController.class);

    @Autowired
    private AliPayConfig aliPayConfig;

    @Autowired
    private OrdersService orderService; // 假设你有这个service

    @Autowired
    private OrdersMapper ordersMapper;

    /**
     * 创建支付宝支付
     */
    @PostMapping("/create")
    public void createPayment(@RequestBody Map<String, String> params, HttpServletResponse response) throws IOException {
        try {
            String orderNo = params.get("orderNo");
            String amount = params.get("amount");
            String subject = params.getOrDefault("subject", "商品支付");

//            // 日志：打印所有关键参数
//            logger.info("[Alipay] appId: {}", aliPayConfig.getAppId());
//            logger.info("[Alipay] gatewayUrl: {}", aliPayConfig.getGatewayUrl());
//            logger.info("[Alipay] privateKey: {}...{}", aliPayConfig.getPrivateKey().substring(0, 10), aliPayConfig.getPrivateKey().substring(aliPayConfig.getPrivateKey().length() - 10));
//            logger.info("[Alipay] publicKey: {}...{}", aliPayConfig.getPublicKey().substring(0, 10), aliPayConfig.getPublicKey().substring(aliPayConfig.getPublicKey().length() - 10));
//            logger.info("[Alipay] notifyUrl: {}", aliPayConfig.getNotifyUrl());
//            logger.info("[Alipay] returnUrl: {}", aliPayConfig.getReturnUrl());
//            logger.info("[Alipay] signType: {}", aliPayConfig.getSignType());
//            logger.info("[Alipay] orderNo: {}, amount: {}, subject: {}", orderNo, amount, subject);

            // 1. 创建AlipayClient
            AlipayClient alipayClient = new DefaultAlipayClient(
                    aliPayConfig.getGatewayUrl(),
                    aliPayConfig.getAppId(),
                    aliPayConfig.getPrivateKey(),
                    "json",
                    "UTF-8",
                    aliPayConfig.getPublicKey(),
                    aliPayConfig.getSignType());

            // 2. 设置请求参数
            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
            alipayRequest.setReturnUrl(aliPayConfig.getReturnUrl());
            alipayRequest.setNotifyUrl(aliPayConfig.getNotifyUrl());

            // 3. 构建业务参数
            Map<String, String> bizContent = new HashMap<>();
            bizContent.put("out_trade_no", orderNo);
            bizContent.put("total_amount", amount);
            bizContent.put("subject", subject);
            bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
            bizContent.put("timeout_express", "30m");

            String bizContentJson = JSON.toJSONString(bizContent);
            logger.info("[Alipay] bizContent: {}", bizContentJson);
            alipayRequest.setBizContent(bizContentJson);

            // 4. 请求支付宝并返回表单HTML
            String form = alipayClient.pageExecute(alipayRequest).getBody();
            logger.info("[Alipay] 返回form内容前100字符: {}", form != null && form.length() > 100 ? form.substring(0, 100) : form);
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().write(form);
            response.getWriter().flush();
        } catch (AlipayApiException e) {
            logger.error("支付创建失败", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.setContentType("text/plain;charset=UTF-8");
            response.getWriter().write("支付创建失败: " + e.getMessage());
        }
    }

    /**
     * 支付宝异步通知处理
     */
    @PostMapping("/notify")
    public String paymentNotify(HttpServletRequest request) {
        try {
            // 1. 转换请求参数
            Map<String, String> params = convertParams(request);

            // 2. 验证签名（使用支付宝SDK验证）
            boolean signVerified = Factory.Payment.Common()
                    .verifyNotify(params);

            if (!signVerified) {
                logger.warn("支付宝异步通知签名验证失败");
                return "failure";
            }

            // 3. 处理业务逻辑
            String tradeStatus = params.get("trade_status");
            String outTradeNo = params.get("out_trade_no");
            String totalAmount = params.get("total_amount");

            if ("TRADE_SUCCESS".equals(tradeStatus)) {
                // 直接在控制层查找并更新订单
                Orders order = ordersMapper.selectOne(
                    new QueryWrapper<Orders>().eq("order_sn", outTradeNo)
                );
                if (order != null) {
                    order.setStatus(1); // 假设1为已支付
                    order.setUpdateTime(new Date());
                    order.setPaymentMethod("支付宝");
                    if (totalAmount != null) {
                        try {
                            order.setTotalAmount(Double.valueOf(totalAmount));
                        } catch (Exception ignored) {}
                    }
                    order.setUpdateTime(new java.util.Date());
                    ordersMapper.updateById(order);
                    logger.info("订单支付成功，订单号: {}，金额: {}，状态已更新为PAID", outTradeNo, totalAmount);
                } else {
                    logger.error("未找到订单，订单号: {}", outTradeNo);
                    return "failure";
                }
                return "success";
            }
        } catch (Exception e) {
            logger.error("支付宝异步通知处理失败", e);
        }
        return "failure";
    }

    /**
     * 支付宝同步跳转
     */
    @GetMapping("/return")
    public String paymentReturn(HttpServletRequest request) {
        // 支付成功后跳转到首页 http://localhost:5173/main3
        return "<script>window.location.href='http://localhost:5173/main3'</script>";
    }

    /**
     * 转换请求参数为Map
     */
    private Map<String, String> convertParams(HttpServletRequest request) {
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();

        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        return params;
    }
}